#include "KeyValue.h"

// #define MAX_LINE_LENGTH 256
// #define IS_DISP_ASCII(x) (((x) >= ' ') && ((x) <= '~'))
// #define KEYVALUE_LOG(fmt, ...)  printf("[KeyValue.c|%d] "fmt"\r\n",__LINE__,##__VA_ARGS__)



#define KEYVALUE_LOG(fmt, ...)  printf("[KeyValue.c|%d] "fmt"\r\n",__LINE__,##__VA_ARGS__)

#define __max(a,b) (((a) > (b)) ? (a) : (b))
#define __min(a,b) (((a) < (b)) ? (a) : (b))

typedef struct _KeyValueLine
{
    char key[MAX_KEY_LENGTH];
    char value[MAX_VALUE_LENGTH];
    KeyValueLinePtr next;
}KeyValueLine;    // char sep; //分隔符默认使用=

eDICT_ERR Dict_Init(Dict * dict)
{
    if(dict == NULL)return eDICT_ERR_PARA_INVALID; 
    dict->head = NULL;
    dict->size = 0;
    return eDICT_ERR_OK;
}
static eDICT_ERR Dict_Add(Dict * dict, KeyValueLine * line)
{
    KeyValueLinePtr p = dict->head;
    if(dict == NULL || line == NULL || line->key == NULL || line->value == NULL)return eDICT_ERR_PARA_INVALID; 
    if(p == NULL) //说明是第一个节点
        dict->head = line;
    else
    {
        while(p->next) //找到指针最后
        {
            if(strcmp(p->key, line->key) == 0)
            {
                return eDICT_ERR_KEY_IS_EXSIT; 
            }
            p = p->next;
        }
        p->next = line;
    }
    dict->size++;
    return eDICT_ERR_OK;
}

eDICT_ERR Dict_Create(Dict * dict, const char * key, const char * value)
{
    if(dict == NULL || key == NULL || value == NULL)return eDICT_ERR_PARA_INVALID;
    KeyValueLinePtr p = (KeyValueLinePtr)malloc(sizeof(KeyValueLine));
    if(p == NULL) {KEYVALUE_LOG("memory not enough"); return eDICT_ERR_MEM_NOT_ENOUGH;}
    strncpy(p->key, key, __min(MAX_KEY_LENGTH - 1,strlen(key)));
    p->key[__min(MAX_KEY_LENGTH - 1,strlen(key))] = '\0';
    strncpy(p->value, value, __min(MAX_VALUE_LENGTH - 1,strlen(value)));
    p->value[__min(MAX_VALUE_LENGTH - 1,strlen(value))] = '\0';
    p->next = NULL;
    return Dict_Add(dict, p);
}

eDICT_ERR Dict_Del(Dict * dict,const char * key)
{
    KeyValueLinePtr p = dict->head, q = dict->head; //q 用于记录上一个节点
    eDICT_ERR ret = eDICT_ERR_KEY_NOT_FOUND;  //默认键值是没有找到的
    if(dict == NULL || key == NULL)return eDICT_ERR_PARA_INVALID;
    while(p != NULL)//找到指针最后
    {
        if(strcmp(p->key, key) == 0)
        {
            q->next = p->next;
            dict->size--;
            free(p);
            ret = eDICT_ERR_OK;
            break;
        }
        q = p;
        p = p->next;
    }
    return ret;
}
eDICT_ERR Dict_GetValue(Dict * dict, char* key, char* value)
{
    KeyValueLinePtr p = dict->head; 
    eDICT_ERR ret = eDICT_ERR_KEY_NOT_FOUND;  //默认键值是没有找到的
    if(dict == NULL || key == NULL || value == NULL)return eDICT_ERR_PARA_INVALID;
    while(p != NULL )//找到指针最后
    {
        if(strcmp(p->key, key) == 0)
        {
            strcpy(value, p->value);
            ret = eDICT_ERR_OK;
            break;
        }
        p = p->next;
    }
    return ret;
}
eDICT_ERR Dict_SetValue(Dict * dict, char* key, char* value)
{
    KeyValueLinePtr p = dict->head; 
    eDICT_ERR ret = eDICT_ERR_KEY_NOT_FOUND;  //默认键值是没有找到的
    if(dict == NULL || key == NULL || value == NULL)return eDICT_ERR_PARA_INVALID;
    while(p != NULL)//找到指针最后
    {
        if(strcmp(p->key, key) == 0)
        {
            strncpy(p->value, value, __min(strlen(value), MAX_VALUE_LENGTH - 1));
            p->value[__min(strlen(value), MAX_VALUE_LENGTH - 1)] = '\0';
            ret = eDICT_ERR_OK;
            break;
        }
        p = p->next;
    }
    return ret;
}

eDICT_ERR Dict_Dumps(Dict * dict, char* str)
{
    KeyValueLinePtr p = dict->head; 
    eDICT_ERR res = eDICT_ERR_OK;
    if(dict == NULL || str == NULL)return eDICT_ERR_PARA_INVALID;
    while(p != NULL)
    {
        int ret = sprintf(str,"%s=%s\r\n",p->key, p->value);
        if(ret == -1) {res = eDICT_ERR_MEM_NOT_ENOUGH; break;}
        str += ret; 
        p = p->next;//写入成功的话，接着往下写
    }
    *str = '\0';
    return res;
}
eDICT_ERR Dict_Loads(Dict * dict,char* str)
{
    eDICT_ERR res = eDICT_ERR_OK;
    char* p_str = str;
    if(dict == NULL || str == NULL)return eDICT_ERR_PARA_INVALID;
    while(*p_str != '\0')
    {
        KEYVALUE_LOG("strlen = %d",strlen(p_str));
        KeyValueLine* new_line = (KeyValueLine *)malloc(sizeof(KeyValueLine));
        if(new_line == NULL){ KEYVALUE_LOG("Memory not enough");return eDICT_ERR_MEM_NOT_ENOUGH;}
        uint16_t key_index = 0,val_index = 0;
        new_line->next = NULL;
        while((*p_str != '=')  && (*p_str != '\0') && (key_index < MAX_KEY_LENGTH))
        {
            new_line->key[key_index] = *p_str;
            p_str++;
            key_index++;
            if((*p_str == '\r') || (*p_str == '\n'))break;
        }
        if(key_index < MAX_KEY_LENGTH && (*p_str == '=')) //key的长度合法
            {new_line->key[key_index] = '\0'; key_index = 0; p_str++;} //跳过等号
        while ((*p_str != '\r') && (*p_str != '\n')  && (*p_str != '\0') && (val_index < MAX_VALUE_LENGTH))
        {
            new_line->value[val_index] = *p_str;
            p_str++;
            val_index++;
        }
        if(val_index < MAX_VALUE_LENGTH && (*p_str == '\r')) //value的长度合法
            {p_str++;} //跳过\r
        if(val_index < MAX_VALUE_LENGTH && ((*p_str == '\n') || (*p_str == '\0'))) //value的长度合法
        {//跳过\n
            new_line->value[val_index] = '\0';
            val_index = 0;
            p_str++;
            Dict_Add(dict,new_line); 
        }
    }
    return res;
}

eDICT_ERR Dict_Clears(Dict * dict)
{
    KeyValueLinePtr p = dict->head, q = dict->head; 
    eDICT_ERR ret = eDICT_ERR_OK;
    if(dict == NULL)return eDICT_ERR_PARA_INVALID;
    while(p != NULL)
    {
        q = p->next; //暂存next 
        ret = Dict_Del(dict,p->key);
        p = q;
    }
    return ret;
}
